package com.zl.basis.sys;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;

import com.zl.basis.log.TimberUtil;
import com.zl.basis.sign.MD5;
import com.zl.basis.util.StringUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.UUID;

public class DeviceUtil {
    private static final String TAG = "DeviceUtil";

    public static boolean install(String apkPath) {
        TimberUtil.d(TAG, "apkPath =" + apkPath);
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行pm install命令
            String command = "pm install -r " + apkPath + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder msg = new StringBuilder();
            String line;
            // 读取命令的执行结果
            while ((line = errorStream.readLine()) != null) {
                msg.append(line);
            }
            TimberUtil.d(TAG, "install msg is " + msg);
            // 如果执行结果中包含Failure字样就认为是安装失败，否则就认为安装成功
            if (!msg.toString().contains("Failure")) {
                result = true;
            }
        } catch (Exception e) {
            TimberUtil.e(TAG, e.getMessage());
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                TimberUtil.e(TAG, e.getMessage());
            }
        }
        return result;
    }

    public static boolean reboot() {
        try {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream out = new DataOutputStream(process.getOutputStream());
            out.writeBytes("reboot \n");
            out.writeBytes("exit\n");
            out.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void reboot(Context mContext) {
        PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        powerManager.reboot("");
    }

    public static String getPackName(Context mContext) {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
            return packageInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    public static String getDeviceId(Context mContext) {
        String deviceId;
        deviceId = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
        deviceId = deviceId + Build.SERIAL;
        if (StringUtil.isEmpty(deviceId)) {
            deviceId = UUID.randomUUID().toString();
        }
        return MD5.digest(deviceId);
    }

    public static String getDeviceSerial() {
        return Build.SERIAL;
    }

    public static int getNumberOfCPUCores() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
            return 1;
        }
        int cores;
        try {
            cores = new File("/sys/devices/system/cpu/").listFiles(pathname -> {
                String path = pathname.getName();
                if (path.startsWith("cpu")) {
                    for (int i = 3; i < path.length(); i++) {
                        if (path.charAt(i) < '0' || path.charAt(i) > '9') {
                            return false;
                        }
                    }
                    return true;
                }
                return false;
            }).length;
        } catch (SecurityException e) {
            cores = 4;   //这个常量得自己约定
        } catch (NullPointerException e) {
            cores = 4;
        } catch (Exception e) {
            cores = 4;
        }
        return cores;
    }

}
